/* eslint-disable react-hooks/exhaustive-deps */
import React, { Suspense } from 'react'
import { Spin } from 'antd'
import { Switch, Route, useLocation } from 'react-router-dom'
import RedirectRouterView from './RedirectRouterView'
import menus from './menus'
import NoAccess from './../views/NoAccess'
function getIndex (menus, pathname) {
  let index = -1
  // 查询第一层级的满足条件
  index = menus.findIndex(item => item.path === pathname)

  if (index < 0) { // 1 级没有查找到数据，开始查找二级
    let arr = []
    menus.forEach(item => {
      if (item.children) {
        arr.push(item.children.findIndex(item => item.path === pathname))
      }
    });
    // console.log('555', arr)  // [-1, -1, -1, -1, -1] ｜ [-1, -1, -1, 2, -1]
    // // 数组倒叙取第一个
    index = arr.sort((a, b) => b-a)[0]
  }
  return index
}
function RouterView(props) {
  const { pathname } = useLocation()
  // console.log(pathname)
  const renderRoute = (menus) => {
    return menus.map(item => {
      if (item.children) {
        return renderRoute(item.children)
      } else {
        // 如果 menus 的数组中包含现在地址栏的地址
        // console.log('1' + pathname, getIndex(menus, pathname))
        if (getIndex(menus, pathname) < 0) {
          return <Route
          path={ pathname }
          key={pathname}
          render = { () => <NoAccess/>} />
        }
        return item.path === '/' ? null : <Route
          path={ item.path }
          key={item.path}
          exact
          component = { item.component } />
        }
    })
  }


  return (
    <Suspense fallback={<div className="loading"><Spin size="large" /></div>} >
      <Switch>
        {/* <Redirect path="/" exact to="/home" /> */}
        {
          renderRoute(menus)
        }
       
        <RedirectRouterView />
       
      </Switch>
    </Suspense>
)
}

export default RouterView
